package yhao.infra.feature.dubbo.filter.validation;

import yhao.infra.feature.dubbo.api.ValidationArgs;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;

/**
 * Created by yoara on 2016/6/13.
 * JSR-303
 * @see org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
 */
public class ValidationBean {
    private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    private Validator defaultValidator = factory.getValidator();

    /**
     * 校验传递的参数
     * @param param
     */
    public ValidationResult validationParam(ValidationArgs param){
        return checkParam(param, getValidator());
    }

    private ValidationResult checkParam(ValidationArgs param, Validator validator) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<Object>> violations = validator.validate(param);
        if(violations!=null&&violations.size()>0){
            result.setHasError(true);
            for(ConstraintViolation violation : violations){
                ValidationErrorMessage errorMessage = new ValidationErrorMessage();
                errorMessage.setMessage(violation.getMessage());
                errorMessage.setClassName(violation.getRootBeanClass().getSimpleName());
                errorMessage.setProperty(violation.getPropertyPath().toString());
                result.addErrorMessage(errorMessage);
            }
        }
        return result;
    }

    private Validator getValidator(){
        Validator validator;
        try{
            validator = defaultValidator;
        }catch(Exception e){
            return null;
        }
        return validator;
    }
}
